import { Message as ElMsg } from 'element-ui'

let currMsg = null

function showMsg(options) {
  if (currMsg == null) {
    currMsg = ElMsg(options)
  } else {
    currMsg.close()
    currMsg = null
    showMsg(options)
  }
  return currMsg
}

function _buildParams(opt, t) {
  const type = opt.type || t
  if (typeof opt === 'string')
    return {
      type,
      message: opt,
      offset: 90,
      duration: 2 * 1000,
    }
  return {
    offset: 90,
    ...opt,
    type
  }
}

Msg.success = options => showMsg(_buildParams(options, 'success'))
Msg.warning = options => showMsg(_buildParams(options, 'warning'))
Msg.info = options => showMsg(_buildParams(options, 'info'))
Msg.error = options => showMsg(_buildParams(options, 'error'))

export default function Msg(options) {
  return showMsg(_buildParams(options))
}
